from tkinter import *
import tkinter.messagebox
from tkinter import ttk
from tkinter import font
from src.backend.patient_b import PatientBackend

class PatientFrontend:
    """Frontend UI for patient management"""
    
    def __init__(self, master, user_type='admin'):
        self.master = master
        self.user_type = user_type
        self.backend = PatientBackend()
        
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()

        #ATTRIBUTES
        self.pat_ID = IntVar()
        self.pat_first_name = StringVar()
        self.pat_last_name = StringVar()
        self.pat_dob = StringVar()
        self.pat_address = StringVar()
        self.pat_gender = StringVar()
        self.pat_blood_group = StringVar()
        self.pat_email = StringVar()
        self.pat_phone = StringVar()
        self.pat_emergency_contact = StringVar()
        self.pat_emergency_phone = StringVar()
        self.pat_medical_history = StringVar()

        self.create_ui()

    def create_ui(self):
        """Create the user interface"""
        #TITLE
        self.lblTitle = Label(self.frame, text="PATIENT REGISTRATION FORM", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=30)
        
        #FRAME
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="groove", bg="#C0C0C0", bd=3)
        self.LoginFrame.grid(row=1, column=0, padx=10, pady=10)
        
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="groove", bg="#C0C0C0", bd=3)
        self.LoginFrame2.grid(row=2, column=0, padx=10, pady=10)
        
        self.create_form_fields()
        self.create_buttons()

    def create_form_fields(self):
        """Create form input fields"""
        #==LABELS          
        self.lblpatid = Label(self.LoginFrame, text="PATIENT ID", font="Arial 11 bold", bg="#C0C0C0", bd=10)
        self.lblpatid.grid(row=0, column=0, sticky=W, padx=5, pady=5)
        self.lblpatid = Entry(self.LoginFrame, font="Arial 11", bd=2, relief="sunken", textvariable=self.pat_ID)
        self.lblpatid.grid(row=0, column=1, padx=5, pady=5)
        
        self.lblPatFirst = Label(self.LoginFrame, text="FIRST NAME", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblPatFirst.grid(row=1, column=0)
        self.lblPatFirst = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_first_name)
        self.lblPatFirst.grid(row=1, column=1)

        self.lblPatLast = Label(self.LoginFrame, text="LAST NAME", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblPatLast.grid(row=2, column=0)
        self.lblPatLast = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_last_name)
        self.lblPatLast.grid(row=2, column=1)

        self.lblgender = Label(self.LoginFrame, text="GENDER", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblgender.grid(row=3, column=0)
        self.lblgender = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_gender)
        self.lblgender.grid(row=3, column=1)

        self.lblDOB = Label(self.LoginFrame, text="DOB (YYYY-MM-DD)", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblDOB.grid(row=4, column=0)
        self.lblDOB = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_dob)
        self.lblDOB.grid(row=4, column=1)
        
        self.lblbgrp = Label(self.LoginFrame, text="BLOOD GROUP", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblbgrp.grid(row=5, column=0)
        self.lblbgrp = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_blood_group)
        self.lblbgrp.grid(row=5, column=1)
        
        self.lblCon = Label(self.LoginFrame, text="PHONE NUMBER", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblCon.grid(row=0, column=2)
        self.lblCon = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_phone)
        self.lblCon.grid(row=0, column=3)
        
        self.lblAlt = Label(self.LoginFrame, text="EMERGENCY CONTACT", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblAlt.grid(row=1, column=2)
        self.lblAlt = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_emergency_contact)
        self.lblAlt.grid(row=1, column=3)
        
        self.lbleid = Label(self.LoginFrame, text="EMAIL", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lbleid.grid(row=2, column=2)
        self.lbleid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_email)
        self.lbleid.grid(row=2, column=3)

        self.lblEmergPhone = Label(self.LoginFrame, text="EMERGENCY PHONE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblEmergPhone.grid(row=3, column=2)
        self.lblEmergPhone = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_emergency_phone)
        self.lblEmergPhone.grid(row=3, column=3)

        self.lbladd = Label(self.LoginFrame, text="ADDRESS", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lbladd.grid(row=4, column=2)
        self.lbladd = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_address)
        self.lbladd.grid(row=4, column=3)

        self.lblMedHist = Label(self.LoginFrame, text="MEDICAL HISTORY", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblMedHist.grid(row=5, column=2)
        self.lblMedHist = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, relief="sunken", textvariable=self.pat_medical_history)
        self.lblMedHist.grid(row=5, column=3)

    def create_buttons(self):
        """Create action buttons"""
        #==BUTTONS 
        self.button2 = Button(self.LoginFrame2, text="SUBMIT", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.INSERT_PAT)
        self.button2.grid(row=3, column=1, padx=5, pady=5)
        
        self.button3 = Button(self.LoginFrame2, text="UPDATE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.UPDATE_PAT)
        self.button3.grid(row=3, column=2, padx=5, pady=5)
        
        self.button4 = Button(self.LoginFrame2, text="DELETE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.D_DISPLAY)
        self.button4.grid(row=3, column=3, padx=5, pady=5)
        
        self.button5 = Button(self.LoginFrame2, text="SEARCH", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.S_DISPLAY)
        self.button5.grid(row=3, column=4, padx=5, pady=5)
        
        self.button6 = Button(self.LoginFrame2, text="EXIT", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.Exit)
        self.button6.grid(row=3, column=5, padx=5, pady=5)
        
        # Add Global Search button only for root users
        if self.user_type == 'root':
            self.button7 = Button(self.LoginFrame2, text="GLOBAL SEARCH", width=15, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.GLOBAL_SEARCH)
            self.button7.grid(row=4, column=1, columnspan=2, pady=10)

    #FUNCTION TO INSERT DATA IN PATIENT FORM
    def INSERT_PAT(self):
        try:
            # Get and validate phone number
            phone = self.pat_phone.get().strip()
            phone_digits = ''.join(c for c in phone if c.isdigit())
            if len(phone_digits) < 7:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Phone number must have at least 7 digits")
                return
            
            # Get and validate emergency phone if provided
            emergency_phone = self.pat_emergency_phone.get().strip()
            emergency_phone_digits = ''
            if emergency_phone:
                emergency_phone_digits = ''.join(c for c in emergency_phone if c.isdigit())
                if len(emergency_phone_digits) < 7:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Emergency phone must have at least 7 digits")
                    return
            
            # Get form data - store only digits for phone numbers to fit VARCHAR(15)
            patient_data = {
                'first_name': self.pat_first_name.get().strip(),
                'last_name': self.pat_last_name.get().strip(),
                'date_of_birth': self.pat_dob.get().strip(),
                'gender': self.pat_gender.get().strip(),
                'blood_group': self.pat_blood_group.get().strip() or None,
                'address': self.pat_address.get().strip(),
                'email': self.pat_email.get().strip(),
                'phone': phone_digits,  # Store only digits
                'emergency_contact': self.pat_emergency_contact.get().strip() or None,
                'emergency_phone': emergency_phone_digits if emergency_phone_digits else None,  # Store only digits
                'medical_history': self.pat_medical_history.get().strip() or None
            }
            
            # Validate data
            is_valid, message = self.backend.validate_patient_data(patient_data)
            if not is_valid:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", message)
                return
            
            # Add patient to database
            patient_id = self.backend.add_patient(patient_data)
            
            if patient_id:
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", f"Patient added successfully with ID: {patient_id}")
                self.clear_form()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to add patient")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def clear_form(self):
        """Clear all form fields"""
        self.pat_ID.set(0)
        self.pat_first_name.set("")
        self.pat_last_name.set("")
        self.pat_dob.set("")
        self.pat_gender.set("")
        self.pat_blood_group.set("")
        self.pat_address.set("")
        self.pat_email.set("")
        self.pat_phone.set("")
        self.pat_emergency_contact.set("")
        self.pat_emergency_phone.set("")
        self.pat_medical_history.set("")
        
    #FUNCTION TO UPDATE DATA IN PATIENT FORM
    def UPDATE_PAT(self):
        try:
            patient_id = self.pat_ID.get()
            if not patient_id:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter Patient ID to update")
                return
            
            # Check if patient exists
            patient = self.backend.get_patient(patient_id)
            if not patient:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Patient not found")
                return
            
            # Get form data
            update_data = {}
            if self.pat_first_name.get().strip():
                update_data['first_name'] = self.pat_first_name.get().strip()
            if self.pat_last_name.get().strip():
                update_data['last_name'] = self.pat_last_name.get().strip()
            if self.pat_dob.get().strip():
                update_data['date_of_birth'] = self.pat_dob.get().strip()
            if self.pat_gender.get().strip():
                update_data['gender'] = self.pat_gender.get().strip()
            if self.pat_blood_group.get().strip():
                update_data['blood_group'] = self.pat_blood_group.get().strip()
            if self.pat_address.get().strip():
                update_data['address'] = self.pat_address.get().strip()
            if self.pat_email.get().strip():
                email = self.pat_email.get().strip()
                # Validate email format
                if '@' not in email or '.' not in email:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Invalid email format")
                    return
                update_data['email'] = email
            if self.pat_phone.get().strip():
                phone = self.pat_phone.get().strip()
                # Validate phone number (allow digits, spaces, dashes, parentheses)
                phone_digits = ''.join(c for c in phone if c.isdigit())
                if len(phone_digits) < 7:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Phone number must have at least 7 digits")
                    return
                update_data['phone'] = phone_digits  # Store only digits
            if self.pat_emergency_contact.get().strip():
                update_data['emergency_contact'] = self.pat_emergency_contact.get().strip()
            if self.pat_emergency_phone.get().strip():
                emergency_phone = self.pat_emergency_phone.get().strip()
                # Validate emergency phone number
                phone_digits = ''.join(c for c in emergency_phone if c.isdigit())
                if len(phone_digits) < 7:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Emergency phone must have at least 7 digits")
                    return
                update_data['emergency_phone'] = phone_digits  # Store only digits
            if self.pat_medical_history.get().strip():
                update_data['medical_history'] = self.pat_medical_history.get().strip()
            
            if not update_data:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "No data to update")
                return
            
            # Update patient
            if self.backend.update_patient(patient_id, update_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Patient updated successfully")
                self.clear_form()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to update patient")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
            
    #FUNCTION TO EXIT PATIENT REGISTRATION WINDOW
    def Exit(self):            
        self.master.destroy()

    #FUNCTION TO OPEN DELETE PATIENT DISPLAY WINDOW
    def D_DISPLAY(self):
        self.newWindow = Toplevel(self.master)
        self.app = DMenu(self.newWindow, self.backend)
        
    #FUNCTION TO OPEN SEARCH PATIENT DISPLAY WINDOW
    def S_DISPLAY(self):
        self.newWindow = Toplevel(self.master)
        self.app = SMenu(self.newWindow, self.backend)
    
    #FUNCTION TO OPEN GLOBAL SEARCH WINDOW (ROOT ONLY)
    def GLOBAL_SEARCH(self):
        self.newWindow = Toplevel(self.master)
        self.app = GlobalSearchMenu(self.newWindow, self.backend)

#CLASS FOR DISPLAY MENU FOR DELETE PATIENT
class DMenu:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        self.del_pid = IntVar()
        self.lblTitle = Label(self.frame, text="DELETE WINDOW", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=50)
        #=FRAME=
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        #==LABELS          
        self.lblpatid = Label(self.LoginFrame, text="ENTER PATIENT ID TO DELETE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblpatid.grid(row=0, column=0)
        self.lblpatid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.del_pid)
        self.lblpatid.grid(row=0, column=1)

        self.DeleteB = Button(self.LoginFrame2, text="DELETE", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.DELETE_PAT)
        self.DeleteB.grid(row=3, column=1, padx=5, pady=5)

    #FUNCTION TO DELETE DATA IN PATIENT FORM
    def DELETE_PAT(self):        
        try:
            patient_id = self.del_pid.get()
            if not patient_id:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter Patient ID to delete")
                return
            
            # Check if patient exists
            patient = self.backend.get_patient(patient_id)
            if not patient:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Patient record not found")
                return
            
            # Confirm deletion
            result = tkinter.messagebox.askyesno("HOSPITAL DATABASE SYSTEM", 
                                               f"Are you sure you want to delete patient {patient[1]} {patient[2]}?")
            if result:
                if self.backend.delete_patient(patient_id):
                    tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Patient deleted successfully")
                    self.del_pid.set(0)
                else:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to delete patient")
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

#CLASS FOR SEARCH MENU FOR SEARCH PATIENT
class SMenu:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("HOSPITAL MANAGEMENT SYSTEM")
        self.master.geometry("1500x700+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        self.s_pid = StringVar()
        self.lblTitle = Label(self.frame, text="SEARCH WINDOW", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=25)
        #=FRAME=
        self.LoginFrame = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame.grid(row=1, column=0)
        self.LoginFrame2 = Frame(self.frame, width=400, height=80, relief="ridge", bg="#C0C0C0", bd=20)
        self.LoginFrame2.grid(row=2, column=0)
        
        #==LABELS          
        self.lblpatid = Label(self.LoginFrame, text="ENTER PATIENT ID OR NAME TO SEARCH", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.lblpatid.grid(row=0, column=0)
        self.lblpatid = Entry(self.LoginFrame, font="Arial 11 bold", bd=2, textvariable=self.s_pid)
        self.lblpatid.grid(row=0, column=1)

        self.SearchB = Button(self.LoginFrame2, text="SEARCH", width=10, font="Arial 11 bold", bg="#C0C0C0", relief="raised", bd=2, command=self.SEARCH_PAT)
        self.SearchB.grid(row=0, column=1, padx=5, pady=5)
        
    #FUNCTION TO SEARCH DATA IN PATIENT FORM
    def SEARCH_PAT(self):
        try:
            search_term = self.s_pid.get().strip()
            if not search_term:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Please enter Patient ID or Name to search")
                return
            
            # Clear previous search results
            self.clear_search_results()
            
            # Try to search by ID first (if it's a number)
            patient = None
            if search_term.isdigit():
                patient = self.backend.get_patient(int(search_term))
            
            # If not found by ID, search by name/phone/email
            if not patient:
                patients = self.backend.search_patients(search_term)
                if patients:
                    if len(patients) == 1:
                        patient = patients[0]
                    else:
                        # Multiple results - show selection dialog
                        self.show_multiple_results(patients)
                        return
            
            if patient:
                self.display_patient_info(patient)
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "PATIENT RECORD NOT FOUND")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def clear_search_results(self):
        """Clear previous search result labels"""
        for widget in self.LoginFrame.winfo_children():
            if isinstance(widget, Label) and widget.grid_info().get('row', 0) > 0:
                widget.destroy()
    
    def show_multiple_results(self, patients):
        """Show dialog for multiple search results"""
        result_window = Toplevel(self.master)
        result_window.title("Multiple Patients Found")
        result_window.geometry("600x400")
        result_window.config(bg="#C0C0C0")
        
        Label(result_window, text="Multiple patients found. Please select one:", 
              font="Arial 11 bold", bg="#C0C0C0").pack(pady=10)
        
        frame = Frame(result_window, bg="#C0C0C0")
        frame.pack(fill=BOTH, expand=True, padx=20, pady=10)
        
        for i, patient in enumerate(patients):
            btn_text = f"ID: {patient[0]} - {patient[1]} {patient[2]}"
            btn = Button(frame, text=btn_text, font="Arial 11", bg="#C0C0C0", relief="raised", bd=2,
                        command=lambda p=patient: self.select_patient(p, result_window))
            btn.pack(fill=X, pady=2)
    
    def select_patient(self, patient, window):
        """Select a patient from multiple results"""
        window.destroy()
        self.display_patient_info(patient)
    
    def display_patient_info(self, patient):
        """Display patient information"""
        # Patient data structure: (patient_id, first_name, last_name, gender, date_of_birth, 
        # blood_group, address, email, phone, emergency_contact, emergency_phone, medical_history)
        
        self.l1 = Label(self.LoginFrame, text="PATIENT ID", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l1.grid(row=1, column=0)
        self.dis1 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=str(patient[0]))
        self.dis1.grid(row=1, column=1)
        
        self.l2 = Label(self.LoginFrame, text="FIRST NAME", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l2.grid(row=2, column=0)
        self.dis2 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=patient[1])
        self.dis2.grid(row=2, column=1)

        self.l3 = Label(self.LoginFrame, text="LAST NAME", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l3.grid(row=3, column=0)
        self.dis3 = Label(self.LoginFrame, font="Arial 11 bold", bg="#C0C0C0", bd=2, text=patient[2])
        self.dis3.grid(row=3, column=1)

        self.l4 = Label(self.LoginFrame, text="GENDER", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l4.grid(row=4, column=0)
        self.dis4 = Label(self.LoginFrame, font="Arial 11 bold", bg="#C0C0C0", bd=2, text=patient[3])
        self.dis4.grid(row=4, column=1)
        
        self.l5 = Label(self.LoginFrame, text="DOB", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l5.grid(row=5, column=0)
        self.dis5 = Label(self.LoginFrame, font="Arial 11 bold", bg="#C0C0C0", bd=2, text=str(patient[4]))
        self.dis5.grid(row=5, column=1)
        
        self.l6 = Label(self.LoginFrame, text="BLOOD GROUP", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l6.grid(row=1, column=2)
        self.dis6 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=patient[5] or "N/A")
        self.dis6.grid(row=1, column=3)
        
        self.l7 = Label(self.LoginFrame, text="ADDRESS", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l7.grid(row=2, column=2)
        self.dis7 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=patient[6])
        self.dis7.grid(row=2, column=3)
        
        self.l8 = Label(self.LoginFrame, text="EMAIL", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l8.grid(row=3, column=2)
        self.dis8 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=patient[7])
        self.dis8.grid(row=3, column=3)

        self.l9 = Label(self.LoginFrame, text="PHONE", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l9.grid(row=4, column=2)
        self.dis9 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=patient[8])
        self.dis9.grid(row=4, column=3)

        self.l10 = Label(self.LoginFrame, text="EMERGENCY CONTACT", font="Arial 11 bold", bg="#C0C0C0", bd=22)
        self.l10.grid(row=5, column=2)
        self.dis10 = Label(self.LoginFrame, font="Arial 11 bold", bd=2, bg="#C0C0C0", text=patient[9] or "N/A")
        self.dis10.grid(row=5, column=3)

#CLASS FOR GLOBAL SEARCH MENU (ROOT ONLY)
class GlobalSearchMenu:
    def __init__(self, master, backend):    
        self.master = master
        self.backend = backend
        self.master.title("GLOBAL SEARCH - ALL PATIENTS")
        self.master.geometry("1200x600+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        
        self.lblTitle = Label(self.frame, text="GLOBAL PATIENT SEARCH", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=25)
        
        # Create Treeview for displaying all patients
        self.tree_frame = Frame(self.frame, bg="#C0C0C0")
        self.tree_frame.grid(row=1, column=0, padx=20, pady=10)
        
        # Define columns
        columns = ('ID', 'First Name', 'Last Name', 'Gender', 'DOB', 'Blood Group', 'Phone', 'Email', 'Address')
        self.tree = ttk.Treeview(self.tree_frame, columns=columns, show='headings', height=15)
        
        # Define headings
        for col in columns:
            self.tree.heading(col, text=col)
            self.tree.column(col, width=120)
        
        # Add scrollbar
        scrollbar = ttk.Scrollbar(self.tree_frame, orient=VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        # Pack treeview and scrollbar
        self.tree.pack(side=LEFT, fill=BOTH, expand=True)
        scrollbar.pack(side=RIGHT, fill=Y)
        
        # Buttons frame
        self.button_frame = Frame(self.frame, bg="#C0C0C0")
        self.button_frame.grid(row=2, column=0, pady=10)
        
        self.refresh_btn = Button(self.button_frame, text="REFRESH", width=15, font="Arial 11 bold", 
                                bg="#C0C0C0", relief="raised", bd=2, command=self.refresh_data)
        self.refresh_btn.pack(side=LEFT, padx=5)
        
        self.edit_btn = Button(self.button_frame, text="EDIT SELECTED", width=15, font="Arial 11 bold", 
                              bg="#C0C0C0", relief="raised", bd=2, command=self.edit_selected)
        self.edit_btn.pack(side=LEFT, padx=5)
        
        self.delete_btn = Button(self.button_frame, text="DELETE SELECTED", width=15, font="Arial 11 bold", 
                                bg="#C0C0C0", relief="raised", bd=2, command=self.delete_selected)
        self.delete_btn.pack(side=LEFT, padx=5)
        
        self.close_btn = Button(self.button_frame, text="CLOSE", width=15, font="Arial 11 bold", 
                               bg="#C0C0C0", relief="raised", bd=2, command=self.close_window)
        self.close_btn.pack(side=LEFT, padx=5)
        
        # Load initial data
        self.refresh_data()
    
    def refresh_data(self):
        """Refresh the patient data in the treeview"""
        try:
            # Clear existing data
            for item in self.tree.get_children():
                self.tree.delete(item)
            
            # Get all patients from database
            patients = self.backend.get_all_patients()
            
            # Insert data into treeview
            for patient in patients:
                self.tree.insert('', 'end', values=(
                    patient[0],  # ID
                    patient[1],  # First Name
                    patient[2],  # Last Name
                    patient[4],  # Gender (patient[4] in database)
                    str(patient[3]),  # DOB (patient[3] in database)
                    patient[5] or "N/A",  # Blood Group
                    patient[8],  # Phone
                    patient[7],  # Email
                    patient[6]   # Address
                ))
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error loading data: {str(e)}")
    
    def edit_selected(self):
        """Edit the selected patient"""
        selection = self.tree.selection()
        if not selection:
            tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Please select a patient to edit")
            return
        
        # Get selected patient data
        item = self.tree.item(selection[0])
        patient_id = item['values'][0]
        
        # Open edit window
        self.edit_window = Toplevel(self.master)
        self.edit_app = EditPatientWindow(self.edit_window, patient_id, self.backend, self.refresh_data)
    
    def delete_selected(self):
        """Delete the selected patient"""
        selection = self.tree.selection()
        if not selection:
            tkinter.messagebox.showwarning("HOSPITAL DATABASE SYSTEM", "Please select a patient to delete")
            return
        
        # Get selected patient data
        item = self.tree.item(selection[0])
        patient_id = item['values'][0]
        patient_name = f"{item['values'][1]} {item['values'][2]}"
        
        # Confirm deletion
        result = tkinter.messagebox.askyesno("HOSPITAL DATABASE SYSTEM", 
                                           f"Are you sure you want to delete patient {patient_name}?")
        if result:
            try:
                if self.backend.delete_patient(patient_id):
                    tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Patient deleted successfully")
                    self.refresh_data()
                else:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to delete patient")
            except Exception as e:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")
    
    def close_window(self):
        """Close the global search window"""
        self.master.destroy()

#CLASS FOR EDIT PATIENT WINDOW
class EditPatientWindow:
    def __init__(self, master, patient_id, backend, refresh_callback):
        self.master = master
        self.patient_id = patient_id
        self.backend = backend
        self.refresh_callback = refresh_callback
        
        self.master.title("EDIT PATIENT")
        self.master.geometry("800x600+0+0")
        self.master.config(bg="#C0C0C0")
        self.frame = Frame(self.master, bg="#C0C0C0")
        self.frame.pack()
        
        # Get patient data
        self.patient = self.backend.get_patient(patient_id)
        if not self.patient:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Patient not found")
            self.master.destroy()
            return
        
        # Create form variables
        self.pat_first_name = StringVar(value=self.patient[1])
        self.pat_last_name = StringVar(value=self.patient[2])
        self.pat_dob = StringVar(value=str(self.patient[4]))
        self.pat_address = StringVar(value=self.patient[6])
        self.pat_gender = StringVar(value=self.patient[3])
        self.pat_blood_group = StringVar(value=self.patient[5] or "")
        self.pat_email = StringVar(value=self.patient[7])
        self.pat_phone = StringVar(value=self.patient[8])
        self.pat_emergency_contact = StringVar(value=self.patient[9] or "")
        self.pat_emergency_phone = StringVar(value=self.patient[10] or "")
        self.pat_medical_history = StringVar(value=self.patient[11] or "")
        
        # Title
        self.lblTitle = Label(self.frame, text="EDIT PATIENT", font="Arial 16 bold", bg="#C0C0C0", fg="#000080")
        self.lblTitle.grid(row=0, column=0, columnspan=2, pady=20)
        
        # Form frame
        self.form_frame = Frame(self.frame, bg="#C0C0C0")
        self.form_frame.grid(row=1, column=0, padx=20, pady=10)
        
        # Form fields
        row = 0
        Label(self.form_frame, text="FIRST NAME:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_first_name, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="LAST NAME:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_last_name, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="GENDER:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_gender, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="DOB (YYYY-MM-DD):", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_dob, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="BLOOD GROUP:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_blood_group, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="PHONE:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_phone, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="EMAIL:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_email, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="ADDRESS:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_address, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="EMERGENCY CONTACT:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_emergency_contact, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="EMERGENCY PHONE:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_emergency_phone, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        row += 1
        
        Label(self.form_frame, text="MEDICAL HISTORY:", font="Arial 11 bold", bg="#C0C0C0").grid(row=row, column=0, sticky=W, pady=5)
        Entry(self.form_frame, textvariable=self.pat_medical_history, font="Arial 11", width=30).grid(row=row, column=1, pady=5)
        
        # Buttons
        self.button_frame = Frame(self.frame, bg="#C0C0C0")
        self.button_frame.grid(row=2, column=0, pady=20)
        
        Button(self.button_frame, text="SAVE", width=15, font="Arial 11 bold", 
               bg="#C0C0C0", relief="raised", bd=2, command=self.save_changes).pack(side=LEFT, padx=5)
        Button(self.button_frame, text="CANCEL", width=15, font="Arial 11 bold", 
               bg="#C0C0C0", relief="raised", bd=2, command=self.master.destroy).pack(side=LEFT, padx=5)
    
    def save_changes(self):
        """Save the changes to the patient"""
        try:
            # Validate and process phone number
            phone = self.pat_phone.get().strip()
            phone_digits = ''.join(c for c in phone if c.isdigit())
            if len(phone_digits) < 7:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Phone number must have at least 7 digits")
                return
            
            # Validate and process emergency phone if provided
            emergency_phone = self.pat_emergency_phone.get().strip()
            emergency_phone_digits = None
            if emergency_phone:
                emergency_phone_digits = ''.join(c for c in emergency_phone if c.isdigit())
                if len(emergency_phone_digits) < 7:
                    tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Emergency phone must have at least 7 digits")
                    return
            
            update_data = {
                'first_name': self.pat_first_name.get().strip(),
                'last_name': self.pat_last_name.get().strip(),
                'date_of_birth': self.pat_dob.get().strip(),
                'gender': self.pat_gender.get().strip(),
                'blood_group': self.pat_blood_group.get().strip() or None,
                'address': self.pat_address.get().strip(),
                'email': self.pat_email.get().strip(),
                'phone': phone_digits,  # Store only digits
                'emergency_contact': self.pat_emergency_contact.get().strip() or None,
                'emergency_phone': emergency_phone_digits,  # Store only digits
                'medical_history': self.pat_medical_history.get().strip() or None
            }
            
            if self.backend.update_patient(self.patient_id, update_data):
                tkinter.messagebox.showinfo("HOSPITAL DATABASE SYSTEM", "Patient updated successfully")
                self.refresh_callback()
                self.master.destroy()
            else:
                tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", "Failed to update patient")
                
        except Exception as e:
            tkinter.messagebox.showerror("HOSPITAL DATABASE SYSTEM", f"Error: {str(e)}")

